package com.example.zuuldemo.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 新建拦截器
 *
 * @author 文希
 * @create 2019-05-26 14:49
 */
@Component
public class TokenFilter extends ZuulFilter {
    /**
     * 拦截类型
     * pre 进入zuul就拦截
     * router 在路由时拦截
     * post 认为路由完后，拦截
     * error 有错误拦截
     *
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 拦截次序
     * 数字越小，越在前面
     *
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 是否拦截
     *
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 拦截后做什么
     * 1、做token的验证
     *
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
//        System.out.println("拦截了");
//        System.out.println("嘿嘿");
        //该类就是zuul所有的request都放进来了
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        String token = request.getParameter("access_token");
        if (token == null) {
            requestContext.setResponseBody("token is not null");
            requestContext.setResponseStatusCode(401);
            requestContext.setSendZuulResponse(false); //能否继续下下面的拦截器做
        }
        if (!"123456".equals(token)) {

            requestContext.setResponseBody("token is error");
            requestContext.setResponseStatusCode(401);
            requestContext.setSendZuulResponse(false); //能否继续下下面的拦截器做
        }
        requestContext.setSendZuulResponse(true); //继续往下走
        return null;
    }
}
